#ifndef SPEAKER_H
#define SPEAKER_H

#include <QAudioOutput>
#include <QObject>

class Speaker : public QObject
{
    Q_OBJECT

public:
    Speaker(QObject *parent = nullptr) : QObject(parent)
    {
        QAudioFormat format;
        format.setSampleRate(44100);
        format.setChannelCount(1);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::SignedInt);

        QAudioDeviceInfo dev = QAudioDeviceInfo::defaultOutputDevice();
        if (!dev.isFormatSupported(format)) {
            format = dev.nearestFormat(format);
        }

        m_audioOutput = new QAudioOutput(dev, format, parent);
        qreal linearVolume = QAudio::convertVolume(90 / qreal(100),
                                                   QAudio::LogarithmicVolumeScale,
                                                   QAudio::LinearVolumeScale);

        m_audioOutput->setVolume(linearVolume);
        qAudioDevice = m_audioOutput->start();
    }

    ~Speaker() = default;

public slots:
    void pushSound(const char *buffer, qint64 size)
    {
        while (size) {
            qint64 wrote = qAudioDevice->write(buffer, size);
            size -= wrote;
            buffer += wrote;
        }
    }

private:
    QAudioOutput *m_audioOutput{nullptr};
    QIODevice *qAudioDevice{nullptr};
};

#endif // SPEAKER_H
